package com.good.webadmin.config;

import com.good.domain.models.ErrorCode;
import com.good.domain.models.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * controller 增强器
 *
 * @author sam
 * @since 2017/7/17
 */
@ControllerAdvice
@Slf4j
public class MyControllerAdvice {

    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Result myErrorHandler(MyException ex) {

        if(ex.getCode()== ErrorCode.Error401.getCode()){
            return new Result(ErrorCode.Error401, ex.getMessage());
        }

        return new Result(ErrorCode.Error500, ex.getMessage());
    }

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception ex) {
        ex.printStackTrace();
        return new Result(ErrorCode.Error500, ex.getMessage());
    }



}
